package ru.mcfr.oxygen.framework.operations;

import ro.sync.contentcompletion.xml.CIElement;
import ro.sync.contentcompletion.xml.WhatElementsCanGoHereContext;
import ro.sync.ecss.extensions.api.*;
import ro.sync.ecss.extensions.api.node.AuthorDocumentFragment;

import javax.swing.text.BadLocationException;
import java.util.List;

public class InsertNumericListOperation implements AuthorOperation {


    public void doOperation(AuthorAccess authorAccess, ArgumentsMap args) throws IllegalArgumentException, AuthorOperationException {

        try {
            int caretOffset = authorAccess.getEditorAccess().getCaretOffset();
            final AuthorSchemaManager schemaManager = authorAccess.getDocumentController().getAuthorSchemaManager();
            AuthorDocumentController controller = authorAccess.getDocumentController();
            WhatElementsCanGoHereContext ctxt = schemaManager.createWhatElementsCanGoHereContext(caretOffset);

            final List<CIElement> childrenElements = schemaManager.getChildrenElements(ctxt);
            for (int i = 0; i < childrenElements.size(); i++) {
                final int index = i;
                CIElement element = childrenElements.get(index);

                if (element.getName() == "нумерованный_список") {

                    AuthorDocumentFragment frag = schemaManager.createAuthorDocumentFragment(element);
                    AuthorDocumentFragment nf = null;

                    try {
                        nf = controller.createNewDocumentFragmentInContext("<нумерованный_список id=\"\"><элемент_списка id=\"\"><абзац id=\"\"/></элемент_списка></нумерованный_список>", caretOffset);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        authorAccess.getWorkspaceAccess().showInformationMessage(ex.getMessage());
                    }

                    if (nf != null)
                        authorAccess.getDocumentController().insertFragment(caretOffset, nf);
                    else
                        authorAccess.getDocumentController().insertFragment(caretOffset, frag);


                }
            }

        } catch (BadLocationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    public ArgumentDescriptor[] getArguments() {
        // TODO Auto-generated method stub
        return null;
    }


    public String getDescription() {
        return "Вставить нумерованный спсиок";
    }

}
